package logic

import (
	"context"
	"errors"
	"time"

	"jinrigaoping/pkg/constant"
	"jinrigaoping/rpc/sys/internal/code"
	"jinrigaoping/rpc/sys/internal/model"
	"jinrigaoping/rpc/sys/internal/svc"
	"jinrigaoping/rpc/sys/sys"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type SysUserAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSysUserAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SysUserAddLogic {
	return &SysUserAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SysUserAddLogic) SysUserAdd(in *sys.SysUserAddReq) (*sys.SysUserAddRes, error) {

	sysUser, err := l.svcCtx.SysUserModel.FindOneByAccount(l.ctx, in.Account)
	if err != nil && !errors.Is(err, sqlx.ErrNotFound) {
		logx.Errorf("FindOneByAccount account: %s error: %v", in.Account, err)
		return nil, err
	}

	if sysUser != nil {
		return nil, code.AccountExists
	}

	// 增加系统用户
	if _, err := l.svcCtx.SysUserModel.Insert(l.ctx, &model.SysUser{
		Account:    in.Account,
		Password:   in.Password,
		Status:     in.Status,
		RoleId:     in.RoleId,
		Nickname:   in.Nickname,
		Phone:      in.Phone,
		Email:      in.Email,
		UserType:   constant.AdminUser,
		Brief:      in.Brief,
		CreateTime: time.Now(),
		UpdateTime: time.Now(),
	}); err != nil {
		logx.Errorf("SysUserAdd params: %v error: %v", in, err)
		return nil, err
	}

	return &sys.SysUserAddRes{}, nil
}
